<template>
  <view class="release-page">
    <up-navbar title="发布鉴定" @rightClick="rightClick" :titleStyle="{color: '#333333' , fontWeight: '500' ,
      fontSize:'34rpx'}" rightText="鉴宝说明" :autoBack="true">
    </up-navbar>
    <view class="release-content">
      <view class="content-title">鉴定信息</view>
      <view class="content-info">
        <view class="info-nav" @click="traesureShow = true">
          <view class="nav-title">藏品类型</view>
          <view class="nav-content">
            <image :src="treasure.image" mode="widthFix" class="content-img"></image>
            <view class="content-name">{{treasure.name}}</view>
            <up-icon name="arrow-right"></up-icon>
          </view>
        </view>
        <view class="info-nav" @click="expertShow = true">
          <view class="nav-title">鉴定专家</view>
          <view class="nav-content">
            <image :src="firstExpertList?firstExpertList.avatar:''" mode="" class="content-img"></image>
            <view class="content-name">{{firstExpertList?firstExpertList.nickname:''}}</view>
            <up-icon name="arrow-right"></up-icon>
          </view>
        </view>
      </view>
      <view class="content-imgs">
        <view class="content-title">藏品图片/视频</view>
        <view class="content-label">尽量上传多角度高清照片，以便鉴定</view>
      </view>
      <view class="img-list">
        <view class="list-img">
          <view class="info-img" v-for="item,index in mustImgList" :key="item.id">
            <up-icon name="close-circle-fill" size="28rpx" color="#333333" class="close-icon"
              @click="onclearImg(index,item.id)" v-show="item.image"></up-icon>
            <image :src="item.image" mode="aspectFit" @click.stop="onAmplifyImg(item.image,'image')"
              v-show="item.image"></image>
            <view class="img-nav" @click="uploadImg(mustImgList,item.id)" v-show="!item.image">
              <view class="img-title">示例图片</view>
            </view>
            <view class="img-name">{{item.name}}</view>
          </view>
          <view class="info-img" v-for="item,index in supplementImg" :key="index">
            <up-icon name="close-circle-fill" size="28rpx" color="#333333" class="close-icon"
              @click="onclearImg(index)"></up-icon>
            <image :src="item" mode="" @click.stop="onAmplifyImg(item,'image')"></image>
            <view class="img-name">其他补充</view>
          </view>
          <view class="info-img">
            <view class="img-nav" @click="uploadImg(supplementImg)">
              <up-icon name="plus-circle" size="48rpx" color="#CCCCCC"></up-icon>
            </view>
            <view class="img-name">其他补充</view>
          </view>
        </view>
        <view class="list-video">
          <view class="video-title">
            <view class="title-name">视频辅助鉴定</view>
            <view class="title-label">(视频不超过30s、100M，禁止上传色情、暴恐、违法视频)</view>
          </view>
          <view class="video-nav">
            <view class="info-img">
              <view class="img-nav" @click="uploadVideo(vedioList)" v-show="!vedioList">
                <image src="@/static/my/icon/camera.png" mode="" class="camera-img"></image>
              </view>
              <up-icon name="close-circle-fill" size="28rpx" color="#333333" class="close-icon" @click="onclearVedio"
                v-show="vedioList"></up-icon>
              <DomVideoPlayer ref="domVideoPlayer" :src="vedioList" muted class="info-video" v-show="vedioList"
                @click="onAmplifyImg(vedioList,'video')" />
              <image src="@/static/home/icon/play.png" mode="aspectFill" class="play-icon" v-show="vedioList"
                @click="onAmplifyImg(vedioList,'video')"></image>
              <view class="img-name">上传视频</view>
            </view>
          </view>
        </view>
      </view>
      <view class="content-imgs">
        <view class="content-title">藏品描述 <view style="color:#E80707;">*</view>
        </view>
        <view class="content-label">（字数不得少于5个字哦）</view>
      </view>
      <view class="content-info">
        <up-textarea v-model="textareaValue" border="none" height="240rpx"
          placeholder="简单介绍鉴宝要求、产品尺寸、时间等相关信息，有助鉴别准确率和估价哦~"></up-textarea>
      </view>
      <view class="content-title">鉴定状态</view>
      <view class="content-status">
        <view class="nav-title">是否公开</view>
        <up-switch v-model="switchValue" activeColor="#A4682F"></up-switch>
      </view>
    </view>
    <view class="selease-btn">
      <view class="btn-label">
        <image src="@/static/home/icon/prompt.png" mode="" class="prompt"></image>
        <view>购前提醒：购买鉴定内容仅供参考，不做任何承诺</view>
      </view>
      <view class="btn-content">
        <view class="content-price">
          <view class="price-num">
            {{expertPrice?expertPrice:0}}
            <view style="font-size: 24rpx;">金币</view>
          </view>
          <view class="price-prompt">
            <up-icon name="checkmark-circle" color="#00C24E" size="28rpx"></up-icon>
            <view>购买即代表同意</view>
            <view style="color: #A4682F;" @click="onAmplifyPage">《免责声明》</view>
          </view>
        </view>
        <view class="content-nav">
          <up-button :text="taskId?'去支付':'去鉴定'" shape="circle" :loading="payLoading" color="#A4682F"
            @click="onIdentify"></up-button>
        </view>
      </view>
    </view>
  </view>
  <payment-order :show="modalShow" v-if="expertPrice && taskId" :taskId="taskId" :price="expertPrice"
    @showClose="modalShow = false" @release="modalShow = false"></payment-order>
  <SelectExpertPopup :show="expertShow" :listData="SelectExpertList" @showClose="expertShow = false"
    @release="onExpertRelease"></SelectExpertPopup>
  <tab-popup :show.sync="traesureShow" :listData="traesureList" @showClose="traesureShow = false"
    @release="onrelease"></tab-popup>
</template>

<script setup>
  import {
    children,
    expertList,
    create,
    submitPay,
    taskIndex
  } from './api.js'
  import {
    ref,
    onUnmounted
  } from 'vue';
  import {
    onLoad,
  } from '@dcloudio/uni-app'
  import SelectExpertPopup from './components/SelectExpert/SelectExpertPopup.vue'
  import DomVideoPlayer from '@/components/DomVideoPlayer/DomVideoPlayer';
  const taskId = ref('')
  const fileList = ref([]);
  const textareaValue = ref('')
  const switchValue = ref(true)
  const modalShow = ref(false)
  const expertShow = ref(false)
  const traesureShow = ref(false)
  const traesureList = ref([])
  const treasure = ref({})
  const supplementImg = ref([])
  const mustImgList = ref([])
  const SelectExpertList = ref([])
  const firstExpertList = ref({})
  const vedioList = ref('')
  const payLoading = ref(false)
  const expertPrice = ref()
  const expertId = ref()

  function onconfirm() {
    uni.navigateBack(-1)
  }

  onLoad(async (e) => {
    traesureList.value = uni.getStorageSync('classificationList')
    if (e && e.expertId) {
      expertId.value = e.expertId
    }
    if (e && e.id) {
      await taskIndexAPi(e.id)

    } else {
      treasure.value = uni.getStorageSync('treasure')
      await childrenApi()
      await expertListApi()
    }
  })
  onUnmounted(() => {
    uni.removeStorageSync('treasure')
  })
  const taskIndexAPi = (async (id) => {
    const res = await taskIndex({
      task_id: id
    })
    if (res && res.code === 1) {
      treasure.value = res.data.category
      firstExpertList.value = res.data.expert
      await childrenApi()
      await expertListApi()
      res.data.task_image.map(e => {
        if (e.category_id == 0) {
          supplementImg.value.push(e.image)
        } else {
          mustImgList.value.map(ele => {
            if (e.category_id === ele.id) {
              ele.image = e.image
            }
          })
        }
      })
      vedioList.value = res.data.vedio
      textareaValue.value = res.data.desc
      switchValue.value = res.data.is_open === 1 ? true : false
    } else {
      uni.showToast({
        title: res.msg,
        icon: 'none'
      })
    }
  })

  function onrelease() {
    traesureShow.value = false
    vedioList.value = ''
    supplementImg.value = []
    textareaValue.value = ''
    expertId.value = ''
    firstExpertList.value = {}
    treasure.value = uni.getStorageSync('treasure')
    childrenApi()
    expertListApi()
  }


  function onUploadAvatar(val) {
    console.log(val, 111)
    const {
      url,
      id
    } = val
    mustImgList.value.map(e => {
      if (e.id == id) {
        e.image = url
      }
    })

  }


  const childrenApi = (async () => {
    const res = await children({
      pid: treasure.value.id
    })
    if (res && res.code === 1) {
      mustImgList.value = res.data
    } else {
      uni.showToast({
        title: res.msg,
        icon: 'none'
      })
    }
  })
  const expertListApi = (async (id) => {
    const res = await expertList({
      category_id: treasure.value.id
    })
    if (res && res.code === 1) {
      SelectExpertList.value = res.data.data
      if (expertId.value) {
        res.data.data.map(e => {
          if (expertId.value == e.id) {
            firstExpertList.value = e
            expertPrice.value = e.price
          }
        })

      } else {
        firstExpertList.value = res.data.data[0]
        expertPrice.value = res.data.data[0] ? res.data.data[0].price : 0
      }
    } else {
      uni.showToast({
        title: res.msg,
        icon: "none"
      })
    }
  })
  const onIdentify = (async () => {
    const arr = supplementImg.value.map(e => {
      return {
        id: 0,
        image: e
      }
    })
    if (!treasure.value.id) {
      uni.showToast({
        title: '请选择藏品类型',
        icon: 'none'
      })
      return
    }
    if (!firstExpertList.value) {
      uni.showToast({
        title: '请选择鉴定专家',
        icon: 'none'
      })
      return
    }
    const arrImg = mustImgList.value.slice().reverse()
    for (let i = arrImg.length - 1; i >= 0; i--) {
      if (!arrImg[i].image) {
        uni.showToast({
          title: `请上传${arrImg[i].name}`,
          icon: 'none'
        })
        return
      }
    }
    if (!textareaValue.value) {
      uni.showToast({
        title: '请输入藏品描述',
        icon: 'none'
      })
      return
    }
    if (textareaValue.value.length < 5) {
      uni.showToast({
        title: '藏品描述的字数不得少于5个字',
        icon: 'none'
      })
      return
    }

    const images = [...mustImgList.value, ...arr]
    if (!taskId.value) {
      const res = await create({
        category_id: treasure.value.id,
        category_name: treasure.value.name,
        expert_id: firstExpertList.value.id,
        desc: textareaValue.value,
        images: images,
        vedio: vedioList.value,
        is_open: switchValue.value ? 1 : 0
      })
      if (res && res.code === 1) {
        taskId.value = res.data.task_id
        modalShow.value = true
      } else {
        uni.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    } else {
      modalShow.value = true
    }
  })


  //清空主体部分图片
  function onMustImtClear(id) {
    mustImgList.value.map(e => {
      if (e.id == id) {
        e.src = ''
      }
    })
  }
  //删除视频
  function onclearVedio() {
    vedioList.value = ''
  }
  //删除图片
  function onclearImg(index, id) {
    console.log(index, id, 111)
    if (id) {
      mustImgList.value.map(e => {
        if (e.id === id) {
          e.image = ''
        }
        return e
      })
    } else {
      supplementImg.value.splice(index, 1)
    }
  }
  //全屏查看
  function onAmplifyImg(url, type) {
    uni.navigateTo({
      url: `/pages/index/fullScreenPreview/FullScreenPreview?type=${type}&src=${url}`
    })
  }
  //图片渲染
  function renderingImg(arr, url, id) {
    const newArr = url.split('.')
    if (newArr[newArr.length - 1] !== 'mp4') {
      if (id) {
        mustImgList.value.map(e => {
          if (e.id == id) {
            e.image = url
          }
          return e
        })
      } else {
        arr.push(url)
      }
    } else {
      vedioList.value = url
      console.log(vedioList.value, 999)
    }
  }

  //  上传头像
  const uploadFilePromise = (url, arr, id) => {
    const token = uni.getStorageSync('userInfo').token
    uni.showToast({
      title: '上传中',
      icon: 'loading'
    })
    return new Promise((resolve, reject) => {
      let a = uni.uploadFile({
        url: `https://ttj.geiqiutiyu.com/api/common/upload`, //测试地址
        // url: 'https://localhost:8080/common/upload', //测试环境
        filePath: url,
        name: 'file',
        formData: {
          user: 'test'
        },
        header: {
          token: token
        },
        success: (res) => {
          const data = JSON.parse(res.data)
          if (data && data.code === 1) {
            resolve(data.data)
            renderingImg(arr, data.data.fullurl, id)
            // arr.value.push(data.data.fullurl)
          } else {
            uni.showToast({
              title: data.msg,
              icon: "none"
            })
          }
        },
        fail(err) {
          uni.showToast({
            title: err.errMsg,
            icon: 'none'
          })
        }
      });
    })
  }
  //选取图片
  const uploadImg = (arr, id) => {
    if (id) {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        success: function(res) {
          uploadFilePromise(res.tempFilePaths[0], arr, id)
        }
      })
    } else {
      uni.chooseImage({
        count: 9,
        sizeType: ['original', 'compressed'],
        success: function(res) {
          for (let i = 0; i < res.tempFilePaths.length; i++) {
            uploadFilePromise(res.tempFilePaths[i], arr, id)
          }
        }
      })
    }
  }
  //选择视频
  const uploadVideo = (arr) => {
    uni.chooseVideo({
      sourceType: ['camera', 'album'],
      maxDuration: '30',
      success: function(res) {
        uploadFilePromise(res.tempFilePath, arr)
      }
    });
  }

  function rightClick() {
    uni.navigateTo({
      url: '/pages/my/otherFunctionPage/describePage'
    })
  }

  function onExpertRelease(val) {
    expertShow.value = false
    firstExpertList.value = val
    expertPrice.value = val.price
  }

  function onAmplifyPage() {
    uni.navigateTo({
      url: '/pages/my/agreementPage/purchase-Agreement'
    })
  }
</script>

<style lang="scss" scoped>
  .release-page {
    background-color: #F2F2F2;
    display: flex;
    flex-direction: column;
    height: 100%;


    ::v-deep .u-navbar--fixed {
      position: sticky;
      top: 0;
      box-sizing: border-box;
      background-color: #fff;
    }

    .release-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      box-sizing: border-box;
      padding: 0 30rpx 20rpx;
      overflow: scroll;

      .content-imgs {
        display: flex;

        .content-label {
          font-size: 24rpx;
          font-weight: 400;
          color: rgba(153, 153, 153, 1);
          margin: 48rpx 0 0 16rpx;
        }
      }

      .content-info {
        width: 690rpx;
        background-color: #fff;
        border-radius: 16rpx;
        margin-top: 30rpx;
        box-sizing: border-box;
        display: flex;
        flex-wrap: wrap;

        ::v-deep .u-textarea {
          padding: 24rpx 30rpx;
          box-sizing: border-box;
        }

        .info-nav {
          display: flex;
          height: 88rpx;
          align-items: center;
          justify-content: space-between;
          width: 690rpx;
          box-sizing: border-box;
          padding: 0 30rpx;

          .nav-title {
            font-size: 28rpx;
            font-weight: 400;
            color: rgba(51, 51, 51, 1);

          }

          .nav-content {
            display: flex;
            align-items: center;

            .content-img {
              width: 40rpx;
              height: 40rpx;
              border-radius: 50%;
            }

            .content-name {
              font-size: 28rpx;
              font-weight: 400;
              color: rgba(51, 51, 51, 1);
              margin: 0 16rpx 0 12rpx;
            }
          }
        }

        .img-other {
          display: flex;
          flex-direction: column;
          align-items: center;
          margin: 12rpx 0;
          position: relative;
          width: 146rpx;
          margin-right: 14rpx;
        }
      }


      .img-list {
        width: 690rpx;
        background-color: #fff;
        border-radius: 16rpx;
        margin-top: 30rpx;
        padding: 40rpx 30rpx 32rpx;
        box-sizing: border-box;

        .list-img {
          width: 100%;
          display: flex;
          flex-wrap: wrap;

        }

        .list-video {
          margin-top: 20rpx;
          display: flex;
          flex-direction: column;

          .video-title {
            font-size: 28rpx;
            font-weight: 500;
            color: #333;

            .title-label {
              font-size: 22rpx;
              font-weight: 400;
              color: #999;
              margin-top: 4rpx;
            }
          }

          .video-nav {
            margin-top: 30rpx;
            display: flex;
            flex-wrap: wrap;
          }
        }

        ::v-deep .u-upload__button {
          margin: 0;
          height: 146rpx !important;
          width: 146rpx !important;
          background-color: transparent;
          border: 2rpx solid #EBEBEB;
        }

        .info-img {
          display: flex;
          flex-direction: column;
          align-items: center;
          margin: 16rpx 0;
          position: relative;
          width: 146rpx;
          margin-right: 14rpx;

          .close-icon {
            position: absolute;
            right: -12rpx;
            top: -12rpx;
            z-index: 1;
          }

          .img-nav {
            width: 146rpx;
            height: 146rpx;
            border-radius: 8rpx;
            background: #FFFFFF;
            box-sizing: border-box;
            border: 2rpx solid #EBEBEB;
            display: flex;
            align-items: center;
            justify-content: center;

            .camera-img {
              height: 48rpx;
              width: 48rpx;
              border: none;
            }

            .img-title {
              font-size: 26rpx;
              font-weight: 400;
              color: #ccc;

            }
          }

          image {
            height: 146rpx;
            width: 146rpx;
            border-radius: 8rpx;
            border: 2rpx solid #EBEBEB;
            box-sizing: border-box;
          }

          ::v-deep .u-upload__wrap__preview__image {
            height: 146rpx !important;
            width: 146rpx !important;
            box-sizing: border-box;
            border: 2rpx solid #EBEBEB;
          }

          ::v-deep .u-upload__wrap__preview {
            margin: 0;
          }

          .img-name {
            font-size: 26rpx;
            font-weight: 400;
            color: rgba(102, 102, 102, 1);
            margin-top: 12rpx;
          }

          .info-video {
            height: 146rpx;
            width: 146rpx;
            border-radius: 8rpx;
            border: 2rpx solid #EBEBEB;
            box-sizing: border-box;
          }

          .play-icon {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -100%);
            height: 48rpx;
            width: 48rpx;
            border: none;
          }
        }

        .info-other {
          flex: 1;
        }

        .info-img:nth-child(4n) {
          margin-right: 0;
        }
      }

      .content-status {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 690rpx;
        height: 96rpx;
        border-radius: 16rpx;
        background: #FFFFFF;
        box-sizing: border-box;
        padding: 0 30rpx;
        margin-top: 34rpx;
        flex: 0 0 auto;

        .nav-title {
          font-size: 28rpx;
          font-weight: 400;
          color: rgba(51, 51, 51, 1);

        }
      }
    }

    .selease-btn {
      width: 750rpx;
      background: #FFFFFF;
      display: flex;
      flex-direction: column;
      align-items: center;
      position: sticky;
      bottom: 0;
      left: 0;
      z-index: 1;

      .btn-label {
        width: 100%;
        height: 64rpx;
        opacity: 1;
        box-shadow: 0rpx -4rpx 12rpx -4rpx rgba(0, 0, 0, 0.1);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 22rpx;
        font-weight: 400;
        color: rgba(102, 102, 102, 1);

        .prompt {
          height: 28rpx;
          width: 28rpx;
          margin-right: 4rpx;
        }
      }

      .btn-content {
        height: 116rpx;
        width: 100%;
        box-sizing: border-box;
        padding: 0 30rpx;
        border-top: 2rpx solid #EBEBEB;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .content-price {
          display: flex;
          flex-direction: column;

          .price-num {
            display: flex;
            align-items: baseline;
            font-size: 44rpx;
            font-weight: 400;
            color: rgba(249, 37, 44, 1);

          }

          .price-prompt {
            display: flex;
            align-items: center;
            color: #999999;
            font-size: 22rpx;
            font-weight: 400;

          }
        }

        .content-nav {
          width: 320rpx;
          height: 88rpx;
          display: flex;
          align-items: center;
        }
      }
    }
  }

  .content-title {
    font-size: 34rpx;
    font-weight: 500;
    color: rgba(51, 51, 51, 1);
    margin-top: 40rpx;
    position: relative;
    width: max-content;
    z-index: 1;
    display: flex;
  }

  .content-title:before {
    content: "";
    width: 100%;
    height: 16rpx;
    opacity: 0.5;
    background: linear-gradient(90deg, $color 0%, transparent 100%);
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 0;
  }

  .amplify-nav {
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;

  }
</style>